package main

import (
	"fmt"
	"github.com/go-extend/exnet"
	"io"
	"log"
	"math/rand"
	"net/http"
	"net/http/pprof"
	"os"
	"time"
    "github.com/prometheus/client_golang/prometheus/promhttp"
	"workstation/cnc/httpserver/metrics"
)

func home(w http.ResponseWriter, r *http.Request) {
	ip := exnet.ClientIP(r)
	httpCode := http.StatusOK
	log.Printf("The current user is accessing \"home\"，user's ip: %s， status code: %v", ip, httpCode)

	if r.URL.Path[1:] == "" {
		fmt.Fprintf(w, "您好，这里是主页！\n\n")
		fmt.Fprintf(w, "查看本地\"VERSION\"请进入：http://localhost:80/version\n\n")
		fmt.Fprintf(w, "查看\"healthz\"请进入：http://localhost:80/healthz\n\n")
		fmt.Fprintf(w, "进入云原生学习笔记请进入：http://localhost:80/cncamp\n\n")
	} else {
		fmt.Fprintf(w, "客户端的request是：%s!，这不是一个正确的目录！", r.URL.Path[1:])
	}

	for k, v := range r.Header {
		//fmt.Fprintf(w, "r.Header.k: %s", k)
		//fmt.Fprintf(w, "r.Header.v: %s", v)
		for _, s := range v {
			w.Header().Set(k, s)
		}
	}
}

func healthz(w http.ResponseWriter, r *http.Request) {
	ip := exnet.ClientIP(r)
	httpCode := http.StatusOK
	log.Printf("The current user is accessing \"healthz\"，user's ip: %s， status code: %v", ip, httpCode)

	io.WriteString(w, "200")
}

func cncamp(w http.ResponseWriter, r *http.Request) {
	ip := exnet.ClientIP(r)
	httpCode := http.StatusOK
	log.Printf("The current user is accessing \"cncamp\"，user's ip: %s， status code: %v", ip, httpCode)

	fmt.Fprintf(w, "您好，这是云原生课程作业！\n\n")
	fmt.Fprintf(w, "模块2作业地址为：https://gitee.com/yuhangy/cnc")
}

func version(w http.ResponseWriter, r *http.Request) {
	ip := exnet.ClientIP(r)
	httpCode := http.StatusOK
	log.Printf("The current user is accessing \"version\"，user's ip: %s， status code: %v", ip, httpCode)

	VERSION := os.Getenv("VERSION")
	if VERSION != "" {
		fmt.Fprintf(w, "您好，本地变量VERSION值为空")
	} else {
		fmt.Fprintf(w, "您好，本地变量VERSION的值为：%s", VERSION)
		w.Header().Set("VERSION", VERSION)
	}

}

func images(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	randInt := rand.Intn(2000)
	time.Sleep(time.Millisecond * time.Duration(randInt))
	w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))
}

func main() {
	http.HandleFunc("/", home)
	http.HandleFunc("/version", version)
	http.HandleFunc("/cncamp", cncamp)
	http.HandleFunc("/healthz", healthz)

	mux := http.NewServeMux()
	mux.HandleFunc("/debug/pprof/", pprof.Index)
	mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
	mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
	mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
	mux.HandleFunc("/images", images)
	if err := http.ListenAndServe("0.0.0.0:80", nil); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
